package com.dudu.utils;

import cn.hutool.captcha.generator.RandomGenerator;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.dudu.model.SMSModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 短信验证码工具类
 */
@Component
public class SMSUtil {
    @Autowired
    private SMSModel smsModel;
    @Autowired
    private RedisTemplate<String , Object> redisTemplate;

    /**
     * 生成短信验证码
     */
    public String generateSMS(String phone) {
        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKEN
        String accountSId = smsModel.getAccountId();
        System.out.println(accountSId+"accountSId");
        String accountToken = smsModel.getAuthToken();
        System.out.println(accountToken+"accountToken");
        //请使用管理控制台中已创建应用的APPID
        String appId = smsModel.getAppId();
        System.out.println(appId+"appId");
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        String to = phone;
        String templateId = "1";   //免费开发测试使用的模板ID为1
        //4位随机数(采用hutool工具生成)
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        String randomNum = randomGenerator.generate(); //4位随机数
        Long expire = 20l;   //有效期
        String[] datas = {randomNum, expire.toString()};
        //发送
        HashMap<String, Object> result = sdk.sendTemplateSMS(to, templateId, datas);
        //结果
        if ("000000".equals(result.get("statusCode"))) {
            //存入redis，设置有效期10s
            redisTemplate.opsForValue().set(phone,randomNum);
            redisTemplate.expire(phone,20L,TimeUnit.SECONDS);
            return randomNum;
        } else {
            return null;
        }
    }

    /**
     * 校验短信验证码
     */
    public boolean validateSMS(String phone, String sms) {
        //取得redis里面的验证码
        Object obj = redisTemplate.opsForValue().get(phone);
        if(Objects.isNull(obj)){
            throw new RuntimeException("验证码已经过期!");
        }
        String sms_redis = (String)obj;
        return sms_redis.equals(sms);

    }
}
